
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.swing.JOptionPane;

import java.util.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.sql.*;
import java.text.*;
import java.util.Date;
import java.text.*;
import java.util.*;
import java.awt.image.BufferedImage;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;

import java.io.*;

import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

import util.MyConnection;

import java.net.*;
import java.awt.Graphics2D;
import java.util.zip.*;
public class uploadandstore extends HttpServlet {
	
		String desktopPath1 = System.getProperty("user.home") + "/Desktop";
		String desktopPath = desktopPath1.replace("\\", "/");
		 int  resizlen;	int hashcode;
		 String filecontent="";
		 String sname="";
		 String snameid="";
		 String FILE_NAME=null;
		 StringBuilder sb=new StringBuilder();
		 byte[] message2=null;
		 byte[] message2key=null;
//		 String iplocation="/////Pondyit/java finised projects 2014/";
//		 String iplocation1="/////Pondyit/java finised projects 2014/uploading1/";
//		 String iplocation2="/////Pondyit/java finised projects 2014/uploading2/";
//		 String iplocation3="/////Pondyit/java finised projects 2014/uploading3/";
		 
		 String iplocation="D:/";
		 String iplocation1="D:/uploading1/";
		 String iplocation2="D:/uploading2/";
		 String iplocation3="D:/uploading3/";
		 
	    public void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
		{
	    	doPost(request,response);
	    	
		}

	    
	    
	    public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException 
		{
	    	HttpSession session=request.getSession();
	    	sname=(String) session.getAttribute("name");
	    	snameid=(String) session.getAttribute("eid");
	    	//sname="mani";
	    	//snameid="D@gmail.com";
	    	RequestDispatcher rp;
	    	String fname="";
	    	File file100 = new File(iplocation+"uploading"+sname);
	    	File file111 = new File(iplocation1);
	    	File file112 = new File(iplocation2);
	    	File file113 = new File(iplocation3);
	    	java.io.File file101 = new File("/downloading");
	    	if(!file100.exists())
	    	    file100.mkdirs();
	    	if(!file111.exists())
	    	    file111.mkdirs();
	    	if(!file112.exists())
	    	    file112.mkdirs();
	    	if(!file113.exists())
	    	    file113.mkdirs();
	    	if(!file101.exists())
	    	    file101.mkdirs();
	    	int lent=0; FileInputStream fs=null; File fi=null;
	    	String saveFile="";
	    	String contentType = request.getContentType();
	    	if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
	    		java.sql.Connection con;
	    		int len;
                String query,query1;
                PreparedStatement pstmt;
	    		
	    	DataInputStream in = new DataInputStream(request.getInputStream());
	    	int formDataLength = request.getContentLength();
	    	byte dataBytes[] = new byte[formDataLength];
	    	int byteRead = 0;
	    	int totalBytesRead = 0;
	    	while (totalBytesRead < formDataLength) {
	    	byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
	    	totalBytesRead += byteRead;
	    	}
	    	String file = new String(dataBytes);
	    	saveFile = file.substring(file.indexOf("filename=\"") + 10);
	    	saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
	    	saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
	    	int lastIndex = contentType.lastIndexOf("=");
	    	String boundary = contentType.substring(lastIndex + 1,contentType.length());
	    	int pos;
	    	pos = file.indexOf("filename=\"");
	    	pos = file.indexOf("\n", pos) + 1;
	    	pos = file.indexOf("\n", pos) + 1;
	    	pos = file.indexOf("\n", pos) + 1;
	    	int boundaryLocation = file.indexOf(boundary, pos) - 4;
	    	int startPos = ((file.substring(0, pos)).getBytes()).length;
	    	int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
	    	fname=saveFile;
	    	saveFile=iplocation+"uploading"+sname+"/"+saveFile;
	    	//saveFile="/////Pondyit/java finised projects 2014/HCL NAMAKKAL/"+saveFile;
	    	File ff = new File(saveFile);
	    	FileOutputStream fileOut = new FileOutputStream(ff);
	    	fileOut.write(dataBytes, startPos, (endPos - startPos));
	    	fileOut.flush();
	    	fileOut.close();
	    	FILE_NAME=fname;
	    	int numberofpart=3;
	    	 File inputFile = new File(saveFile);
	    	       FileInputStream inputStream;
	    	 	        String newFileName;
	            FileOutputStream filePart;
	    	 	        int fileSize = (int) inputFile.length();
	    	 	        int PART_SIZE=fileSize/numberofpart;
	    	         int nChunks = 0, read = 0, readLength = PART_SIZE;
	    	 	        byte[] byteChunkPart;
	    	        try {
	    		            inputStream = new FileInputStream(inputFile);
	    	            while (fileSize > 0) {
	    	 	                if (fileSize <= 5) {
	    	 	                    readLength = fileSize;
	    	 	                }
	    	 	                byteChunkPart = new byte[readLength];
	    	                 read = inputStream.read(byteChunkPart, 0, readLength);
	    	 	                fileSize -= read;
	    		                assert (read == byteChunkPart.length);
	    	 	                nChunks++;
	    		                newFileName = FILE_NAME+snameid;
	    		                String ippath="";
	    		                switch(nChunks-1){
	    		                case 0:
	    		                	ippath=iplocation1;
	    		                	break;
	    		                case 1:
	    		                	ippath=iplocation2;
	    		                	break;
	    		                case 2:
	    		                	ippath=iplocation3;
	    		                	break;
	    		                }
	    	 	                filePart = new FileOutputStream(new File(ippath+newFileName));
	    	 	                filePart.write(byteChunkPart);
	    	 	                filePart.flush();
	    	 	                filePart.close();
	    	 	                byteChunkPart = null;
	    	                filePart = null;
	    		            }
	    	 	            inputStream.close();
	    		        } catch (IOException exception) {
	    	 	            exception.printStackTrace();
	    		        }
//	    		        for(int i=0;i<3;i++){
//	    		        BufferedReader br = null;
//	    		    	 
//	    				try {
//	    		 
//	    					String sCurrentLine;
//	    		 sb.setLength(0);
//	    		 filecontent=null;
//	    					br = new BufferedReader(new FileReader("D:/uploading/"+FILE_NAME+".part"+ Integer.toString(i)));
//	    		 
//	    					while ((sCurrentLine = br.readLine()) != null) {
//	    						//System.out.println(sCurrentLine);
//	    						sb.append(sCurrentLine);
//	    						sb.append("\n");
//	    						
//	    					}
//	    		 
//	    				} catch (IOException e) {
//	    					e.printStackTrace();
//	    				} finally {
//	    					try {
//	    						if (br != null)br.close();
//	    					} catch (IOException ex) {
//	    						ex.printStackTrace();
//	    					}
//	    				}
//	    				//File file1 = new File("D:/uploading/"+FILE_NAME+".part"+ Integer.toString(i));
//	    				//file1.delete();
//	    		 filecontent=sb.toString();
//	    		// call(i);
//	    		 System.out.println(filecontent);
//	    		        }
	    		        String dbname=null;
	    		        call2(dbname="message");
	    		        callrate();
	    		        rp=request.getRequestDispatcher("provider.jsp?success=s");
						rp.forward(request, response);

	}
	}



		



		private void call(int j) {
			// TODO Auto-generated method stub
			String dbname=null;
			switch(j){
			case 0:
				call2(dbname="message");
				break;
			case 1:
				call2(dbname="message2");
				break;
			case 2:
				call2(dbname="message3");
				break;
			}
		}



		private void call2(String db) {
			// TODO Auto-generated method stub
			filecontent="Hello";
			try
			 {    
				PreparedStatement pstmt1=null;
	    		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	    		Date date = new Date();
	    		
	    		java.sql.Connection conn=MyConnection.getConnection();
					 Statement s= conn.createStatement();
					 String query11 = ("insert into "+db+" values(?,?,?,?)");
                    pstmt1 = conn.prepareStatement(query11);
                   
                    
                  
                    pstmt1.setString(1, sname);
                    pstmt1.setString(2, snameid);
                    pstmt1.setString(3,FILE_NAME );
                   pstmt1.setString(4,filecontent); 
                  
                      pstmt1.executeUpdate();
                      conn.close();
                    pstmt1.close();
                   
					 
					}
				catch(Exception ee)
					{
					System.err.println("the sql error="+ee.getMessage());
					}   
		}
		private void callrate() {
			// TODO Auto-generated method stub
			//String upload=null;
			int up=0;
			try
			{
			Statement s= MyConnection.getStatement();		
	 		ResultSet rs = s.executeQuery("select * from rating where sid='"+snameid+"'");	
	 		//ResultSet rs11 = s.executeQuery("select * from informationreg where productname='"+searchstr.toString().trim()+"'");
	 		
 		 if(rs.next())
 		 {
 			System.out.print("upopen");
 			
 			up=rs.getInt("upload");
 			//up=Integer.parseInt(upload);
 		
 		
 		 }
 		 
 	up=up+1;
 		//upload=Integer.toString(up);
			rs.close ();
       
		s.close ();
		}catch(Exception e){
	System.out.println("Exception is ;"+e);
	}
		
		try {              DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
				            String sss=date.toLocaleString();
				            String active="yes";
					        int rs1;
							Statement s= MyConnection.getStatement();
		                     
							rs1=s.executeUpdate("update rating SET upload='"+up+"' where sid='"+snameid+"'");
											
							System.out.print("uploaded");	
										
									}
									catch (Exception e1) {
		
										e1.printStackTrace();
									}
		
		}
}			   	
				   	
				   	
				   	
				  
			
			
		    
	    	
	    	
	

	
	

